package com.yh.utils.extract.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 默认数据源（系统数据源）
 * 包名称：
 * 类名称：DefaultDataSource
 * 类描述：@Description
 * 创建人：@author maliang
 * 创建时间：2019/8/23/14:30
 *
 */
@Configuration
@MapperScan(
        basePackages = {"com.yh.**.dao"},
        sqlSessionFactoryRef = "defaultSqlSessionFactory"
)
@Slf4j
public class DefaultDataSourceConfig {
    private static final Logger logger = LoggerFactory.getLogger(DefaultDataSourceConfig.class);
    @Autowired
    private Environment env;

    @Autowired
    DataSourcePropertes dataSourcePropertes;

    public DefaultDataSourceConfig() {
    }


    @Bean(
            name = {"defaultDataSource"}
    )
    @Primary
    public DataSource defaultDataSource() throws SQLException {
        String sDriver = this.env.getProperty("spring.datasource.driver-class-name");
        if (StringUtils.isEmpty(sDriver)) {
            return null;
        } else {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(this.env.getProperty("spring.datasource.driver-class-name"));
            dataSource.setUrl(this.env.getProperty("spring.datasource.url"));
            dataSource.setUsername(this.env.getProperty("spring.datasource.username"));
            dataSource.setPassword(this.env.getProperty("spring.datasource.password"));
            dataSourcePropertes.setDataSourcePropeties(dataSource);
            return dataSource;
        }
    }

    @Bean(
            name = {"defaultSqlSessionFactory"}
    )
    @Primary
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("defaultDataSource") DataSource defaultDataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(false);
        configuration.setLocalCacheScope(LocalCacheScope.STATEMENT);
        bean.setConfiguration(configuration);
        bean.setDataSource(defaultDataSource);
        bean.setTypeAliasesPackage("com.yhfin.**.model");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        try {
            bean.setMapperLocations(resolver.getResources("classpath*:com/yh/**/dao/**/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            logger.error("mybatis初始化sqlSessionFactoryBean失败", e);
            return null;
        }
    }

    @Bean({"defaultSqlSessionTemplate"})
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(
            name = {"defaultTransactionManager"}
    )
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("defaultDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "defaultJdbcTemplate")
    @Primary
    public JdbcTemplate jdbcTemplate(@Qualifier("defaultDataSource") DataSource defaultDataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        jdbcTemplate.setDataSource(defaultDataSource);
        return jdbcTemplate;
    }

}